//------------------------------------------------------------------------------
#include <QSqlRecord>
#include "CMyMainWindow.h"
#include <QtDebug>
#include <CMyLineEdit.h>
#include <libqt4json.h>
#include "CGlobal.h"
#include "CScript.h"
#include "CMySQL.h"
#include "CRequest.h"
#include "CReportRequestData.h"
#include "CTomcatClient.h"
//------------------------------------------------------------------------------
CMyMainWindow::CMyMainWindow(QString name, QWidget *parent) : QMainWindow(parent) {
	btnPrint=0;
	printPopMenu=0;
	listDocToPrint=0;
	mdiSubWindow=0;
	
	setObjectName(name);
}
//------------------------------------------------------------------------------
CMyMainWindow::~CMyMainWindow(void) {
	delete listDocToPrint;
	
	if(printPopMenu != 0) {
		delete printPopMenu;
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::showFormulaire(QSqlQuery *query, CGlobal::EAction& action) {
	/*QList<QWidget *> objects = findChildren<QWidget *>();
	QSqlRecord record=query->record();
	
	curCode=record.value(primaryKey).toString();
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		
		if(champ != NULL) {
			champ->setValue(record.value(champ->getChamp()));
		}
	}*/
	//FIXME implémenter la méthode
}
//------------------------------------------------------------------------------
bool CMyMainWindow::chargeDonnees(QString quelCode, CGlobal::ESens sens) {
	QString requete;
	QString alias="";
	QString tri;
	QString condition;
	QString pk="";
	QSqlQuery *query;
	bool ret=false;
		
	setCursor(Qt::WaitCursor);
		
	makeRequete(requete, alias);
	
	if(alias != "") {
		pk=alias+".";
	}
	pk+=primaryKey;
		
	switch(sens) {	
		case CGlobal::seNone:
			condition=" WHERE "+pk+"=\""+quelCode+"\"";
			tri="";
			break;
		case CGlobal::sePremier:
			condition="";
			tri=" ORDER BY "+pk+" LIMIT 1";
			break;
		case CGlobal::sePrecedent:
			condition=" WHERE "+pk+" < \""+quelCode+"\"";
			tri=" ORDER BY "+pk+" DESC LIMIT 1";
			break;
		case CGlobal::seSuivant:
			condition=" WHERE "+pk+" > \""+quelCode+"\"";
			tri=" ORDER BY "+pk+" LIMIT 1";
			break;
		case CGlobal::seDernier:
			condition="";
			tri=" ORDER BY "+pk+" DESC LIMIT 1";
			break;
	}
		
	requete+=condition+tri;
		
	if(CMySQL::getInstance()->execQuery(requete, &query)) {
		if(query->next()) {
			CGlobal::EAction action=CGlobal::acNone;
			
			setActionCur(CGlobal::acAffiche);
				
			showFormulaire(query, action);
			
			ret=true;
				
			setActionCur(action);
		}
	}	
	delete query;
		
	setCursor(Qt::ArrowCursor);
		
	return ret;
}
//------------------------------------------------------------------------------
bool CMyMainWindow::chargeDonnees(CGlobal::ESens sens, bool reload) {
	bool ret=false;
	
	setCursor(Qt::WaitCursor);
	
	if(!reload || CDAOManager::getInstance()->load(getDao(), keyValues, sens)) {
		CGlobal::EAction action=CGlobal::acNone;
		
		setActionCur(CGlobal::acAffiche);
		
		showFormulaire(action);
		
		ret=true;
		
		setActionCur(action);
	}
	
	setCursor(Qt::ArrowCursor);
	
	return ret;
}
//------------------------------------------------------------------------------
void CMyMainWindow::clearChamps() {
	QList<QWidget *> objects = findChildren<QWidget *>();
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		
		if(champ != 0) {
			champ->setValue("");
		}
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::initChamps(void) {
	QList<QWidget *> objects = findChildren<QWidget *>();
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		
		if(champ != 0) {
			champ->init();
		}
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::enableChamps(bool enable) {
	QList<QWidget *> objects = findChildren<QWidget *>();
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		if(champ != 0) {
			champ->setStateEnable(enable);
		}
	}
}
//------------------------------------------------------------------------------
bool CMyMainWindow::validChamps(void) {
	QList<QWidget *> objects = findChildren<QWidget *>();
	CScript *script=CScript::getInstance();
	bool ret=true;
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		if(champ != 0)
		{
			if(champ->getValue() == "") {
				if(champ->getAttribut() & atObligatoire) {
					QMessageBox msgBox(	QMessageBox::Warning, QObject::tr("Attention"), 
										QObject::tr("Le champ '")+champ->getDescription()+QObject::tr("' est obligatoire"),
										QMessageBox::Ok);
										msgBox.exec();	
										
										ret=false;
				}
				
				if(champ->getAttribut() & atObligatoireConditionel) {
					ret=!script->isTrue(this, champ->getCondition());
					
					if(!ret) {
						QMessageBox msgBox(	QMessageBox::Warning, QObject::tr("Attention"), 
											champ->getTextCondition(), QMessageBox::Ok);
											msgBox.exec();	
					}
				}
			}
		}
	}
	
	return ret;
}
//------------------------------------------------------------------------------
void CMyMainWindow::loadSchema(void) {
	CTomcatClient tomcatClient;
	QVariantMap schema;
	QString tableName=masterTable;
	
	if(getDao() != 0) {
		tableName=getDao()->getTableName();
	}
	
	if(!tomcatClient.getSchema(tableName, schema)) {
		QMessageBox msgBox(	QMessageBox::Critical , tr("Erreur"), 
							tomcatClient.getLastError(), QMessageBox::Ok);
		
		msgBox.exec();
	}else {
		QVariantMap detail = schema.value("schemas").toMap();
		QList<QWidget *> objects = findChildren<QWidget *>();
		
		foreach(QWidget *object, objects) {
			CChamp * champ=dynamic_cast<CChamp *>(object);
			CChampText * champText=dynamic_cast<CChampText *>(object);

			if(champ != 0) {
				QVariantMap c = detail.value(champ->getChamp()).toMap();
				
				champ->setDescription(c.value("champDescription").toString());
				champ->setAttribut((EAttribut)c.value("attribut").toInt());
				champ->setCondition(c.value("condition").toString());
				champ->setTextCondition(c.value("textCondition").toString());
				champ->setDefaultValue(c.value("defaut").toString());
				champ->setNbDecimal(c.value("nbDecimal").toInt());
				
				if(champText != 0) {
					CMyLineEdit *cmle=dynamic_cast<CMyLineEdit *>(object);
					int maxLen = c.value("len").toInt();
					
					champText->setFormule(c.value("formule").toString());
					champText->setEvalTimes((CCommun::EEValTimes)c.value("evalTime").toInt());
					
					if(cmle != 0 && maxLen != 0) {
						cmle->setMaxLength(maxLen);
					}
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
bool CMyMainWindow::validLiaison(void) {
	QList<QWidget *> objects = findChildren<QWidget *>();
	QString base=CMySQL::getInstance()->getBase();
	bool ret=true;
	
	foreach(QWidget *object, objects) {
		CChamp * champ=dynamic_cast<CChamp *>(object);
		if(champ != 0) {
			if(champ->getValue() != "" && champ->getChampRemp() != "") {
				QString requete;
				QSqlQuery *query;
				
				requete="SELECT "+champ->getChampRemp();
				requete+=" FROM "+champ->getTableRemp();
				requete+=" WHERE "+champ->getChampRemp()+" = \""+champ->getValue()+"\"";
				
				if(CMySQL::getInstance()->execQuery(requete, &query)) {
					ret=(query->size() != 0);
					
					if(!ret) {
						QMessageBox msgBox(QMessageBox::Warning, QObject::tr("Attention"), QObject::tr("Le champ ")+champ->getChamp()+QObject::tr(" n'a pas de corespondance dans la table ")+champ->getTableRemp(), QMessageBox::Ok);
						msgBox.exec();
						
						delete query;
						
						return false;
					}
					
					query->next();
					champ->setValue(query->record().value(champ->getChampRemp()));
				}
				
				delete query;
			}
		}
	}
	return true;
}
//------------------------------------------------------------------------------
void CMyMainWindow::calculChamps(CGlobal::EAction action) {
	QList<QWidget *> objects = findChildren<QWidget *>();
	QString base=CMySQL::getInstance()->getBase();
	CScript *script=CScript::getInstance();
	
	foreach(QWidget *object, objects) {
		CChampText * champ=dynamic_cast<CChampText *>(object);
		if(champ != 0) {
			if(champ->getAttribut() & atChampCalcul) {
				if(	((	action == CGlobal::CGlobal::acAjout || action == CGlobal::CGlobal::acAjoutFromOther || 
						action == CGlobal::CGlobal::acAjoutFromDevis || action == CGlobal::CGlobal::acAjoutFromCommande || 
						action == CGlobal::CGlobal::acAjoutFromClient) && champ->getEvalTimes() & CCommun::evtNew) ||
					(action == CGlobal::CGlobal::acModif && champ->getEvalTimes() & CCommun::evtModif)) {
					champ->setValue(script->eval(this, champ->getFormule()));
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::loadPrintPopupMenu(QToolBar *toolBar) {
	int nb;
	listDocToPrint=new QList<CDAODocToPrintEx *>();
	
	if((nb=CDAOManager::getInstance()->loadDoc2Print(objectName(), listDocToPrint)) != 0) {
		btnPrint=new QToolButton(this);
		btnPrint->setIcon(QIcon(":coMexpert/images/agt_print.png"));
		toolBar->addWidget(btnPrint);
		
		if(nb != 1) {
			int i;
			printPopMenu=new QMenu(this);
			
			for(i=0;i<nb;i++) {
				printPopMenu->addAction(createPrintAction(listDocToPrint->at(i), true));
			}
			
			btnPrint->setMenu(printPopMenu);
			btnPrint->setPopupMode(QToolButton::InstantPopup);
		}else {
			btnPrint->setDefaultAction(createPrintAction(listDocToPrint->at(0), false));
		}
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::print(CDAODocToPrintEx *docToPrint) {
	CRequest request;
	CReportRequestData reportRequestData;
	
	reportRequestData.setReportName(docToPrint->get("reportName").toString());
	reportRequestData.setRender(docToPrint->get("render").toString());
	reportRequestData.setDocName(docToPrint->get("reportName").toString());
	
	for(int i=0;i<docToPrint->count();i++) {
		CDAODocToPrintField *field=docToPrint->at(i);
		
		QString value;
		bool ok=CGlobal::getChampValue(this, field->get("tableName").toString(), field->get("champName").toString(), value);
		if(ok) {
			reportRequestData.addReportParam(field->get("fieldName").toString(), value);
		}
	}
	
	request.setToken(CGlobal::getToken());
	request.setData(&reportRequestData);
	
	CPrintFrm::getInstance()->print(&request, this);
}
//------------------------------------------------------------------------------
QAction * CMyMainWindow::createPrintAction(CDAODocToPrintEx *docToPrint, bool multi) {
	QAction *act;
	
	if(multi) {
		act=new QAction(docToPrint->get("reportTitle").toString(), this);
	}else {
		act=new QAction(QIcon(":coMexpert/images/agt_print.png"), "", this);
		act->setIconVisibleInMenu(true);
	}
	
	act->setData(QVariant::fromValue(docToPrint));
	connect(act, SIGNAL(triggered(bool)), this, SLOT(onPrint(bool)));
	
	return act;
}
//------------------------------------------------------------------------------
void CMyMainWindow::enableBtnPrint(bool enable) {
	if(btnPrint != 0){
		btnPrint->setEnabled(enable);
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::onPrint(bool checked) {
	QAction *act=static_cast<QAction *>(QObject::sender());
	
	if(act != 0) {
		CDAODocToPrintEx *docToPrint=act->data().value<CDAODocToPrintEx *>();
		
		print(docToPrint);
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::on_actPremiereFiche_triggered(void) {
	if(getDao() != 0) {
		chargeDonnees(CGlobal::sePremier);
	}else {
		chargeDonnees("", CGlobal::sePremier);
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::on_actFichePrecedente_triggered(void) {
	if(getDao() != 0) {
		chargeDonnees(CGlobal::sePrecedent);
	}else {
		chargeDonnees(curCode, CGlobal::sePrecedent);
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::on_actFicheSuivante_triggered(void) {
	if(getDao() != 0) {
		chargeDonnees(CGlobal::seSuivant);
	}else {
		chargeDonnees(curCode, CGlobal::seSuivant);
	}
}
//------------------------------------------------------------------------------
void CMyMainWindow::on_actDerniereFiche_triggered(void) {
	if(getDao() != 0) {
		chargeDonnees(CGlobal::seDernier);
	}else {
		chargeDonnees("", CGlobal::seDernier);
	}
}
//------------------------------------------------------------------------------
